<template>
  <div class="app-container legal-wrap">
    <dynamic-legal-create
      ref="dynamicLegal"
      v-model="legalParam"
      :hide-required-asterisk="false"
      :rules="rules"
      :type="type"
      :default-list="defaultList"
      :constructions="comLegalConstruction"
      :flow-structure="processDetail"
      :last-template="lastTemplate"
      :download-loading="downloadLoading"
      @downloadTemplate="downloadTemplate"
      @showPreviewDrawer="showPreviewDrawer"
      @showTemplateDrawer="showTemplateDrawer"
      @partTimeWorkerSelectChange="partTimeWorkerSelectChange"
    />
    <div v-if="!isPartTimeWorker" class="module-box">
      <table-title title="订单信息" style="margin-bottom: 9px;margin-top: 16px;">
        <div class="total-amount-price">
          <img :src="incomeAmountIcon" alt="">
          总含税金额：<span class="price">{{ totalAmount }}</span>
        </div>
        <div v-if="!showMobilePage" class="options-btn-group">
          <el-button size="small" type="primary" class="option-btn" @click="onOrderAdd">添加<i class="el-icon-plus" /></el-button>
          <el-button :disabled="deleteDisable" size="small" type="danger" plain class="option-btn" @click="handleRowsDel">删除</el-button>
        </div>
      </table-title>
      <div v-if="showMobilePage" class="pt10">
        <el-button size="small" type="primary" class="option-btn" @click="onOrderAdd">添加<i class="el-icon-plus" /></el-button>
        <el-button :disabled="deleteDisable" size="small" type="danger" plain class="option-btn" @click="handleRowsDel">删除</el-button>
      </div>
      <dynamicEditTable
        ref="dynamicEditTableRef"
        v-model="orders"
        :list-setting="listSetting"
        :order-private-id="orderPrivateId"
        :is-edit="true"
        :show-add-btn="false"
        :fixed="showMobilePage?false:'right'"
        show-selection
        btn-text="新增订单"
        is-fill
        @onSelectChange="onSelectChange"
        @orderPrivateIdChange="orderPrivateIdChange"
      />
      <!-- 关联合同 -->
      <ContractRelevance ref="contractRelevanceRef" v-model="legalParam.contractList" style="margin-top: 24px" />
    </div>
    <audit-process
      ref="auditProcess"
      :default-aduitor-list="[proposer]"
      :old-audit-info="legalDetail.oldAduitInfo"
      v-model="legalParam.aduitInfo"
      :flow-structure="processDetail"
      :is-modify="Boolean(remodifyId)"
      :disable="Boolean(remodifyId)"
      :is-modify-form="Number(isModifyForm)"
      :current-process-index="Number(currentProcessIndex)"
      @submit="submitFun"
      @getProcess="getProcess"
    />
    <fixed-pagination>
      <div class="center">
        <el-button v-if="!legalId" type="info" size="small" class="back-btn empty-btn-style" @click="toBackStep">上一步</el-button>
        <el-button v-if="setSubmitStatus()" type="primary" size="small" class="submit-btn" @click="submit(!isPartTimeWorker)">发起审批</el-button>
        <el-button v-if="setSaveDraftStatus()" type="info" size="small" class="back-btn empty-btn-style" @click="saveDraft">保存草稿</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">返回列表</el-button>
      </div>
    </fixed-pagination>
    <ContractTemplate
      ref="contractTemplateRef"
      :contract-type="type"
      :preview-path="previewPath"
      :download-loading="downloadLoading"
      @downloadTemplate="downloadTemplate" />
    <ContractPreview
      ref="ContractPreviewRef"
      :file-data="lastTemplate"
      :preview-path="previewPath"
      :download-loading="downloadLoading"
      :show-footer="false"
      is-fill
      @setDownloadParams="downloadPreviewFile"/>
  </div>
</template>
<script>
import { staffAdministrationLegalConstruct as legalConstruction } from '../model/legalConstruction';
import { staffAdminlegalOrderSetting as legalOrderSetting } from '../../module/orderSetting';
import { staffAdministrationLegalRules } from '../model/legalRules';
import DynamicLegalCreate from '../module/dynamicLegalCreate';
import ContractRelevance from '../module/contractRelevance';
import dynamicEditTable from '@/components/Common/dynamicEditTable';
import AuditProcess from '@/components/Common/auditProcess';
import TableTitle from '@/components/Title';
import ContractTemplate from '@/components/legal/contractTemplate/index';
import ContractPreview from '@/components/legal/contractTemplate/contractPreview';
import Common from '../mixins/common';
import incomeAmountIcon from '@/assets/chargeOffDetail/incomeAmount.png';

export default {
  name: 'StallAdministrationLegal',
  components: {
    DynamicLegalCreate,
    AuditProcess,
    TableTitle,
    dynamicEditTable,
    ContractTemplate,
    ContractPreview,
    ContractRelevance
  },
  mixins: [
    Common
  ],
  props: {
    legalDetail: {
      type: Object | String,
      default: () => null
    },
    type: {
      type: String | Number,
      default: ''
    }
  },
  data() {
    return {
      incomeAmountIcon,
      legalOrderSetting,
      staffAdministrationLegalRules,
      legalParam: { // 最终需要上传到接口上的参数
        createInfo: {
          createrDepartment: '',
          creater: '',
          createrPost: '',
          createrId: '',
          createrDepartmentId: '',
          proposer: null,
          proposerId: '',
          proposerAvatar: '',
          departmentId: '',
          post: '--',
          flowCode: ''
        },
        contractInfo: {
          type: 2,
          name: '',
          tempSource: '',
          subject: '',
          oppCompany: '',
          oppCompanyType: '',
          code: '',
          signType: '',
          oppIdentity: '',
          cooperDate: {
            type: 1,
            payWay: '',
            deadlineType: '',
            accountPeriod: '',
            period: '',
            items: [{ payDate: '', timeType: '' }]
          },
          describe: '',
          attachment: [],
          // contractCodes: [{ code: '' }],
          ourStamp: '',
          legalTemplate: '',
          stampType: ''
        },
        submitType: 2,
        aduitInfo: {
          countersignSet: 0,
          process: [],
          senders: []
        },
        contractList: [] // 关联合同列表
      },
      orders: [{
        orderNum: '',
        buyProject: '',
        buyType: [],
        conMonType: [],
        contractPrice: '',
        orderPrivateId: 1
      }], // 关联订单
      orderPrivateId: 1,
      defaultList: {
        'createInfo.proposer': []
      },
      curSelectedRows: [],
      deleteDisable: true,
      comLegalConstruction: [],
      isPartTimeWorker: false // 购销合同选中兼职人员合作
    };
  },
  computed: {
    totalAmount() {
      let total = 0;
      this.orders.forEach(el => {
        if (el.contractPrice) {
          total += Number(el.contractPrice);
        }
      });
      return total.toFixed(2);
    },
    /* comLegalConstruction() {
      return legalConstruction(this.legalConstructionArg);
    }, */
    rules() {
      const tempRules = JSON.parse(JSON.stringify(this.staffAdministrationLegalRules));
      const cooperDate = this.legalParam.contractInfo.cooperDate;
      const type = cooperDate.type;
      const accountPeriod = cooperDate.accountPeriod; // 为4时，period必填
      if (type === 1) { // type为1时 payWay， items 非必填
        const noRequired = ['contractInfo.cooperDate.deadlineType', 'contractInfo.cooperDate.accountPeriod', 'contractInfo.cooperDate.period'];
        noRequired.forEach(item => { tempRules[item][0].required = false; });
      } else { // type 为2时 payWay 非必填 (accountPeriod 为4时，period必填）
        if (accountPeriod === 4) {
          const noRequired = ['contractInfo.cooperDate.payWay'];
          noRequired.forEach(item => { tempRules[item][0].required = false; });
        } else {
          const noRequired = ['contractInfo.cooperDate.payWay', 'contractInfo.cooperDate.period'];
          noRequired.forEach(item => { tempRules[item][0].required = false; });
        }
      }
      return tempRules;
    },
    listSetting() {
      return this.legalOrderSetting;
    }
  },
  created() {
    this.comLegalConstruction = JSON.parse(JSON.stringify(legalConstruction(this.legalConstructionArg)));
  },
  methods: {
    // 购销合同判断是否选中兼职人员合作,选中时隐藏合同模板来源、订单信息和关联合同
    partTimeWorkerSelectChange(status) {
      this.isPartTimeWorker = status;
    },
    onOrderAdd() {
      this.$refs['dynamicEditTableRef'].addValue();
    },
    onSelectChange(list) {
      this.curSelectedRows = list;
      this.deleteDisable = !list.length || !(list.length < this.orders.length);
    },
    orderPrivateIdChange(num) {
      if (!num) return;
      this.orderPrivateId = num;
    },
    handleRowsDel() {
      this.$confirm('确认删除已选中的订单信息吗？', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        let curRow;
        // eslint-disable-next-line no-cond-assign
        while (curRow = this.curSelectedRows.pop()) {
          for (let index = this.orders.length - 1; index >= 0; index--) {
            if (this.orders[index].orderPrivateId === curRow.orderPrivateId) {
              this.orders.splice(index, 1);
            }
          }
        }
      }).catch(_ => {});
    },
    submitFun(senders = []) {
      this.modifySenders = senders;// 存到mixins
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 600) {
        return;
      }
      this.antiShakeTime = timestamp;
      if (this.isSubmit) return;
      const params = JSON.parse(JSON.stringify(this.legalParam));
      if (this.reapplyId) {
        params.submitType = 3;
        params.byReapplyId = this.legalId;
      } else {
        params.submitType = 2;
        if (params.hasOwnProperty('byReapplyId')) delete params.byReapplyId;
      }
      this.remodifyId && (params.byRemodifyId = this.remodifyId);
      params.orders = this.orderPriceSwitch(this.orders, 2);
      delete params.createInfo.creater;
      delete params.createInfo.createrDepartment;
      delete params.createInfo.proposer;
      if (params.contractInfo.cooperDate.type === 1 || params.contractInfo.cooperDate.type === 3) {
        delete params.contractInfo.cooperDate.deadlineType;
        delete params.contractInfo.cooperDate.accountPeriod;
        delete params.contractInfo.cooperDate.period;
      } else {
        delete params.contractInfo.cooperDate.payWay;
      }
      if (this.isSigner === 0) {
        params.aduitInfo = this.removeSigner(params.aduitInfo);
      }
      if (this.legalId && !this.createNew) {
        this.handleModifyData(params);
      }
      const message = (this.legalId && !this.createNew && !this.setSaveDraftStatus()) ? '合同修改成功' : '合同新建成功';
      this.handlePost(params, message);
    }
  }
};
</script>
<style lang="scss" scoped>
.legal-wrap {
  .total-amount-price {
    display: flex;
    align-items: center;
    background-color: #f8f8f8;
    color: #999;
    font-size: 12px;
    font-weight: normal;
    margin-left: 10px;
    padding: 4px 6px;
    border-radius: 4px;
    > img {
      width: 14px;
      margin-right: 5px;
    }
    .price {
      font-size: 14px;
      color: #406eff;
      font-weight: bold;
    }
  }
  .footer-btn-wrap {
    display: flex;
    justify-content: center;
  }
  .module-box {
    // margin-bottom: 40px;
    padding-bottom: 32px;
    .options-btn-group {
      position: absolute;
      right: 0;
      .option-btn {
        padding-left: 12px;
        padding-right: 12px;
      }
    }
  }
}
.empty-btn-style {
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
  width: 80px;
  padding: 7px 0;
  text-align: center;
}
::v-deep .el-form-item__error {
  padding-top: 2px !important;
}
</style>
